<template>
  <view class="page">
    <view class="page-box">
      <scroll-view
        class="scroll-view"
        :scroll-y="true"
        :scroll-into-view="intoView"
      >
        <view class="chat-box">
          <view
            class="chat-item"
            v-for="(item, index) in currentMessage"
            :key="index"
            :id="item.id || index"
          >
            <chat-item
              :chat="item"
              :index="index"
              @preview="onPreview(item, index)"
              @faq="onFaq"
              @exchange="onExchange(item, index)"
            ></chat-item>
          </view>
        </view>
      </scroll-view>
      <SafeAreaView class="fixed-box">
        <view class="fixed">
          <button class="person" open-type="contact">
            转人工客服

            <image
              :src="imgBaseUrlV2 + 'icon_rengong.png'"
              mode=""
              class="icon"
            />
          </button>
          <view class="hd" @click="onPhoneCall">
            <image :src="imgBaseUrlV2 + 'kefu_phone.png'" class="icon" />
          </view>

          <view class="bd">
            <view class="input-box">
              <input
                class="input"
                v-model="dataForm.content"
                placeholder="请输入您要咨询的问题"
                @confirm="onConfirm"
              />

              <view
                class="btn-send"
                :class="{ 'color-active': dataForm.content }"
                @click="onConfirm"
                >发送</view
              >
            </view>
          </view>
        </view>
      </SafeAreaView>
    </view>
    <Message ref="message"></Message>
  </view>
</template>

<script>
import viewModule from "@/common/mixins/view-module";
import { mapState, mapMutations, mapActions } from "vuex";
import { imgBaseUrlV1, imgBaseUrlV2 } from "@/common/config";
import vInput from "@/components/public/input/input";
import ChatItem from "@/components/public/item/chat";
import { debounce, setTime } from "@/utils";
const serviceIcon = imgBaseUrlV2 + "kefu.png";
import {
  getCustomerServiceList,
  addCustomerServiceLog,
} from "@/common/api/contact";
import SafeAreaView from "@/components/safe-area-view/index";
export default {
  mixins: [viewModule],
  components: {
    vInput,
    ChatItem,
    SafeAreaView,
  },
  data() {
    return {
      imgBaseUrlV1,
      imgBaseUrlV2,
      dataForm: {
        content: "",
      },
      intoView: "",
      defaultMessage: {
        id: "1",
        avatar: serviceIcon,
        content: "您好，润滑卫士客服很高兴为您服务！",
      },
      currentMessage: [],
      mixinViewOptions: {
        getURL: "/getCustomerServiceList",
        isPage: true,
        isShowLoading: false,
        reachBottom: false,
        createdIsNeed: false,
        pullDown: false,
      },
      limit: 5,
    };
  },
  computed: {
    ...mapState("User", ["userInfo", "token", "permissions"]),
  },
  methods: {
    ...mapMutations("User", ["logout"]),
    ...mapActions("User", ["getUserInfo"]),
    fetchComplete(err, data, res) {
      console.log("??res1", arguments);
      if (err) this.message.error(res.message || "网络错误,请重试");
      // data = data ? data.data : [];
      console.log(data, "??data 2 ", arguments);
      if (Array.isArray(data) && data.length) {
        this.addMessage(
          {
            type: "faq",
            title: "您想咨询?",
            index: false,
            refresh: false,
            avatar: serviceIcon,
            content: data.map((i) => {
              return {
                ...i,
                label: i.title,
                value: i.content,
              };
            }),
          },
          true
        );
      } else {
        this.message.info("已无更多");
      }
    },
    onNext() {},
    onPhoneCall() {
      let phone = this.$Route.query.contact_mobile;
      if (!phone) return;
      uni.makePhoneCall({
        phoneNumber: phone,
      });
    },
    onExchange(item, index) {
      item.refresh = true;
      setTimeout(() => {
        item.refresh = false;
      }, 500);
      this.page++;
      this.getDataList();
    },
    onFaq(child, cIndex, item, index) {
      console.log(arguments);
      if (child.id && this.userInfo.id) {
        addCustomerServiceLog({
          customer_service_id: child.id,
          user_id: this.userInfo.id,
          user_name: this.userInfo.name,
        });
      }

      this.addMessage(
        {
          type: "text",
          to: "?",
          text: child.value || " ",
        },
        1
      );
      this.issue = true;
      // console.log(arguments);
    },
    onConfirm() {
      if (!this.dataForm.content) {
      } else {
        if (!this.dataForm.content.trim()) {
          this.message.error("请输入您要咨询的问题");
        }
        let res = this.addMessage(
          {
            text: this.dataForm.content,
            self: 1,
          },
          1
        );
        // res.
        getCustomerServiceList({
          title: this.dataForm.content.trim(),
        }).then((res) => {
          if (res.code !== this.$ERR_OK) {
            return;
          }
          let { data } = res;
          let list = data.data || data.list || [];
          if (!list.length) {
          }
          this.addMessage(
            {
              type: "faq",
              title: "您想咨询?",
              index: false,
              refresh: false,
              avatar: serviceIcon,
              content: list.map((i) => {
                return {
                  label: i.title,
                  value: i.content,
                };
              }),
            },
            true
          );
          console.log(res, "??rrr");
        });
        this.dataForm.content = "";
      }
    },
    addMessage(msg, isEnd = false, isHistory = false) {
      // this.pushMessage(msg);
      let u = this.userInfo;
      let avatar =
        "https://rhws.oss-cn-chengdu.aliyuncs.com/1a73a5b18242c8ce58e7c4dd13f55b03.png";
      console.log(msg, "??msg", msg.self, serviceIcon, this.currentMessage);
      if (msg && !msg.self) {
        avatar = serviceIcon;
      }
      let content = msg.text || msg.content || "";
      if (msg.type == "image" && msg.file && msg.file.url) {
        content = msg.file.url;
      } else if (msg.type == "faq") {
        content = content || [];
      } else if (msg.type && msg.type !== "text") {
        content = "未支持的消息类型!";
      }
      let id = "a_d" + Math.round(Math.random() * 1000000000);
      let tmp = this.currentMessage.slice(0).reverse();
      let lastIndex = tmp.findIndex((i) => i.showTime || i === "0"); //获取最后一个有显示时间的
      let lastHasTime;
      if (lastIndex != -1) {
        lastIndex = -lastIndex + tmp.length - 1;
        lastHasTime = this.currentMessage[lastIndex];
      }
      let extend = null;
      let _time = !lastHasTime ? msg.time : lastHasTime.time;
      if (!lastHasTime) {
        if (+new Date() - msg.time >= 5000 * 1000) {
          extend = setTime(msg.time, 1);
        }
      } else if (_time - msg.time < -5000 * 1000) {
        //两个时间大于5分钟的时候
        extend = "0";
      }
      this.currentMessage.push({
        ...msg,
        time: msg.time || +new Date(),
        extend,
        avatar,
        createTime: setTime(msg.time),
        status: 1,
        type: msg.type,
        id,
        content,
      });

      if (isEnd) {
        if (this.currentMessage && this.currentMessage.length) {
          let id = this.currentMessage[this.currentMessage.length - 1].id;
          this.setIntoView(id);
        }
      }
      let last = this.currentMessage.length - 1;
      return {
        index: last,
        item: this.currentMessage[last],
      };
    },
    setIntoView: debounce(function (id) {
      this.$nextTick(() => {
        this.intoView = id;
      });
    }, 80),
  },
  onLoad() {
    setTimeout(() => {
      this.currentMessage.push(this.defaultMessage);
      setTimeout(() => {
        this.getDataList();
      }, 600);
    }, 100);
  },
  watch: {},
};
</script>

<style lang="stylus" scoped>
@import '~@/common/stylus/mixins';
@import '~@/common/stylus/variable';

.page {
  position: relative;
  height: calc(100vh - var(--window-top));
  background-color: #f6f6f6;

  >.page-box {
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
  }
}

.scroll-view {
  flex: 1;
  box-sizing: border-box;
  height: 100%;
  overflow: auto;

  .chat-box {
    padding-bottom: 30rpx;

    &:first-child {
      padding-top: 30rpx;
    }

    >.chat-item {
      margin-bottom: 24rpx;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.fixed {
  display: flex;
  z-index: 3;
  width: 100%;
  left: 0;
  bottom: 0;
  align-items: center;
  min-height: 110rpx;
  padding: 16rpx 24rpx;

  &-box {
    background: #fff;
    box-shadow: 0 0 4rpx #eee;
  }

  >.person {
    position: absolute;
    display: flex;
    bottom: 110%;
    width: 240rpx;
    height: 60rpx;
    background: #FFFFFF;
    border-radius: 30rpx;
    font-size: 30rpx;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    align-items: center;
    justify-content: center;
    color: color-active;

    >.icon {
      display: flex;
      width: 32rpx;
      height: 32rpx;
      margin-left: 10rpx;
    }
  }

  >.hd {
    >.icon {
      display: block;
      width: 58rpx;
      height: 58rpx;
    }

    margin-right: 24rpx;
  }

  >.bd {
    flex: 1;

    >.input-box {
      display: flex;
      height: 72rpx;
      line-height: 72rpx;
      background-color: #eee;
      font-size: 28rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #C9CACA;
      border-radius: 4rpx;

      >.input {
        flex: 1;
        padding: 0 24rpx;
        height: 72rpx;
        line-height: 72rpx;
      }

      >.btn-send {
        flex: 0 0 auto;
        padding: 0 20rpx;

        &.color-active {
          color: color-active;
        }
      }
    }
  }
}
</style>
